package com.frogs.ucenter.controller;

import java.awt.image.BufferedImage;
import java.util.Arrays;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.PrivateKey;
import com.frogs.ucenter.component.UserPermissionHelper;
import com.frogs.ucenter.service.UserService;
import com.google.code.kaptcha.Producer;

/**
 * 验证检查类
 * @author wushubin
 *
 */
@Controller
public class VerifyController extends AbsController { 

	private static Logger log = LoggerFactory.getLogger(VerifyController.class);
	
	private static final String VERIFY_NAME = "/user/verifyName";
	private static final String VERIFY_EMAIL = "/user/verifyEmail";
	private static final String VERIFY_PHONE = "/user/verifyPhone";
	private static final String SHOW_VALIDATECODE = "/showValidateCode";
	
	@Resource
	private UserService userService;
	@Resource
	private UserPermissionHelper userPermissionHelper;
	@Resource
	private Producer captchaProducer;

	@RequestMapping(VERIFY_NAME)
    public String verifyName(ModelMap model, String name) {
    	/*result为true时不存在此用户，result为false时已存在此用户 */
        boolean result;
		try {
			result = userService.verifyName(name);
			model.put("result", result);
	        if (result) {
	        	model.put("chksum", StringUtil.md5(name + Boolean.TRUE.toString(), PrivateKey.HAOYAO_PRIVATE_KEY.getValue()));
	        } else {
	        	model.put("chksum", "null");
	        }
		} catch (Exception e) {
			log.error("func[verifyName] name[{}] exception[{} - {}] desc[fail]",//
					new Object[] { name, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
        
        return null;
    }

    @RequestMapping(VERIFY_PHONE)
    public String verifyPhone(ModelMap model, String phone) {
    	 boolean result;
		try {
			result = userService.verifyPhone(phone);
			 model.put("result", result);
	        if (result) {
	        	model.put("chksum", StringUtil.md5(phone + Boolean.TRUE.toString(), PrivateKey.HAOYAO_PRIVATE_KEY.getValue()));        	
	        } else {
	        	model.put("chksum", "null");
	        }
		} catch (Exception e) {
			log.error("func[verifyPhone] phone[{}] exception[{} - {}] desc[fail]",//
					new Object[] { phone, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
    	
        return null;
    }

    @RequestMapping(VERIFY_EMAIL)
    public String verifyEmail(ModelMap model, String email) throws Exception {
    	boolean result = userService.verifyEmail(email);
   	 	model.put("result", result);
        if (result) {
        	model.put("chksum", StringUtil.md5(email + Boolean.TRUE.toString(), PrivateKey.HAOYAO_PRIVATE_KEY.getValue()));
        } else {
        	model.put("chksum", "null");
        }
        return null;
    }
    
    /**
	 * 显示验证码。
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value=SHOW_VALIDATECODE, method=RequestMethod.GET)
	public void showValidateCode(HttpServletRequest request,
            HttpServletResponse response)throws Exception{
		 // Set to expire far in the past.
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        // create the text for the image
        String capText = captchaProducer.createText();
        buildValidateCodeCookie(capText, request, response,"/","");

        // store the text in the session
        //request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);

        ServletOutputStream out = response.getOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", out);
        try
        {
                out.flush();
        }
        finally
        {
                out.close();
        }
	}
	
}
